import logging
import os

import config
from flask import Flask, render_template
from flask.logging import default_handler
from werkzeug.middleware.proxy_fix import ProxyFix

# from app.models import db
from app.utils.flask_oss import FlaskOSS
# from pony.flask import Pony

oss = FlaskOSS()
# pony = Pony()
# db.bind(**config.PONY)
# db.generate_mapping(create_tables=False)


def create_app():
    _app = Flask(__name__)
    _app.config.from_object(config)
    _app.wsgi_app = ProxyFix(_app.wsgi_app, x_proto=1, x_host=1)

    # if not os.path.exists(config.UPLOADS_PATH):
    #     os.makedirs(config.UPLOADS_PATH)

    # config_db(_app)
    config_logging(_app)
    # config_oss(_app)
    config_jinjia2(_app)
    config_blueprint(_app)

    @_app.errorhandler(404)
    def not_found(error):
        return render_template('error.html', error=error, code=404), 404

    return _app


# def config_db(app):
#     pony.init_app(app)


def config_oss(app):
    oss.init_app(app)


def config_jinjia2(app):
    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True
    # app.jinja_env.globals['APP_TITLE'] = config.APP_TITLE


def config_blueprint(app):
    from .hello import hello_bp
    app.register_blueprint(hello_bp)


def config_logging(app):
    if not os.path.exists(config.LOG_PATH):
        os.makedirs(config.LOG_PATH)

    app.logger.removeHandler(default_handler)
    while app.logger.handlers:
        app.logger.handlers.pop()
    formatter = logging.Formatter(
        '[%(asctime)s %(name)s %(filename)s:%(lineno)s] %(process)d|%(thread)d - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
    # set root logger
    root_logger = logging.getLogger(__name__)
    root_logger.setLevel(logging.DEBUG)

    # FileHandler Info
    class InfoFilter(logging.Filter):
        def filter(self, record):
            if logging.INFO <= record.levelno < logging.ERROR:
                return super().filter(record)
            else:
                return False

    handler_info = logging.FileHandler(filename=app.config.get('LOG_WEB_INFO'),
                                       mode='a',
                                       encoding='utf-8')
    handler_info.setFormatter(formatter)
    handler_info.setLevel(logging.INFO)
    info_filter = InfoFilter()
    handler_info.addFilter(info_filter)
    root_logger.addHandler(handler_info)

    # FileHandler Error
    handler_error = logging.FileHandler(filename=app.config.get('LOG_WEB_ERROR'),
                                        mode='a',
                                        encoding='utf-8')
    handler_error.setFormatter(formatter)
    handler_error.setLevel(logging.ERROR)
    root_logger.addHandler(handler_error)
